package com.rzico.sbl.ui.report

import android.widget.ImageView
import androidx.core.view.isVisible
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityReportWaterGoodsBinding
import com.rzico.sbl.model.CommonData
import com.rzico.sbl.model.ReportGoodsData
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.rzico.sbl.viewmodel.WaterViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.listener.onTabSelectedListener
import com.xinnuo.common_ui.base.*
import com.xinnuo.common_ui.glideExt.loadImage
import com.xinnuo.common_ui.utils.bindLifeCycle
import com.xinnuo.common_ui.utils.subscribeByFinally
import com.xinnuo.slimadapter.SlimAdapter

class ReportWaterGoodsActivity : BaseActivity(R.layout.activity_report_water_goods) {

    private val mBinding by lazy { ActivityReportWaterGoodsBinding.bind(getRootView()) }

    private val mKindList = ArrayList<CommonData>()
    private var mKindId = ""
    private var mKeyWord = ""

    override fun getViewModel() = get<WaterViewModel>()

    override fun initData() {
        setToolbarVisibility(false)

        initLayout()

        getKindData()
    }

    private fun initLayout() {
        mBinding
            .listLayout
            .apply {
                emptyLayout.also {
                    it.emptyHint.text = "暂无相关商品信息！"
                }

                recycleList.also { layout ->
                    layout.loadLinear(
                        refresh = swipeRefresh,
                        onRefresh = { getData(0) },
                        onLoad = {
                            isLoadingMore
                                .conditionFalse {
                                    isLoadingMore = true
                                    getData(pageNum)
                                }
                        }
                    )

                    layout.addItemDecoration(SpaceTBDecoration(hasHeader = false))

                    mAdapter = SlimAdapter.creator()
                        .register<ReportGoodsData>(R.layout.item_water_goods) { jector, bean, _ ->
                            jector.apply {
                                text(R.id.item_goods_name, bean.name)
                                text(R.id.item_goods_price, bean.phPrice.formatDecimal())
                                text(R.id.item_goods_stock, "库存：${bean.phStock ?: 0}")

                                with<ImageView>(R.id.item_goods_img) {
                                    it.loadImage(bean.thumbnail)
                                }

                                clicked(R.id.item_goods_stock) {
                                    startActivityEx<ReportGoodsRecordActivity>(
                                        "goodsId" to bean.id
                                    )
                                }
                            }
                        }
                        .attachTo(layout)
                }
            }
    }

    private fun initTabLayout() {
        mBinding
            .goodsTab
            .apply {
                onTabSelectedListener {
                    onTabSelected {
                        it?.let {
                            mKindId = mKindList[it.position].id

                            getViewModel().cancelRequest()
                            getViewModel().delay { updateList() }
                        }
                    }
                }

                mKindList.forEachIndexed { index, bean ->
                    addTab(newTab().setText(bean.name), index == 0)
                }
            }
    }

    /**
     * 商品分类
     */
    private fun getKindData() {
        getViewModel()
            .productCat(intent.getExtra("shopId"))
            .bindLifeCycle(getLifecycleOwner())
            .subscribeByFinally(
                event = getViewModel(),
                onSuccess = { list ->
                    mKindList.add(
                        CommonData().apply {
                            id = ""
                            name = "全部"
                        }
                    )
                    mKindList.addItems(list.filter { it.name == "桶装水" || it.name == "瓶装水" })

                    initTabLayout()
                }
            )
    }

    /**
     * 报货水站商品列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .goodsList(
                page = index,
                shopId = intent.getExtra("shopId"),
                kindId = mKindId,
                keyWord = mKeyWord,
                onSuccess = {
                    mList.apply {
                        (index == 0)
                            .condition {
                                clear()
                                pageNum = 0
                            }

                        addItems(it)
                        it.notEmpty { pageNum++ }
                    }

                    mAdapter.setDataList(mList)
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh.isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    /**
     * 刷新列表数据
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh.isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        mList.notEmpty {
            mList.clear()
            mAdapter.notifyDataSetChanged()
        }

        getData(0)
    }

}